package org.lex.app.prefs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

abstract class AbstractFileBasedResourceMap extends AbstractResourceMap implements FileBasedResourceMap {
	protected static final String DEFAULT_ENCODING = Charset.defaultCharset().name();
	protected static final String DEFAULT_COMMENT = "application configuration file";
	private File configurationFile = null;
	private String comment = DEFAULT_COMMENT;
	private String encoding = DEFAULT_ENCODING;

	public AbstractFileBasedResourceMap(File configFile) {
		super();
		this.setConfigurationFile(configFile);
	}

	public File getConfigurationFile() {
		return this.configurationFile;
	}

	public void setConfigurationFile(File file) {
		this.configurationFile = file;
	}

	public String getComment() {
		return comment;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	protected InputStream openInputStream() throws IOException {
		if (null == configurationFile)
			throw new NullPointerException("configuration file can't be null");
		if (false == configurationFile.exists())
			throw new IOException("file not exist: " + configurationFile.getAbsolutePath());
		if (false == configurationFile.isFile() || false == configurationFile.canRead())
			throw new IOException("file not readable: " + configurationFile.getAbsolutePath());
		return new FileInputStream(configurationFile);
	}

	protected OutputStream openOutputStream() throws IOException {
		if (null == configurationFile)
			throw new NullPointerException("configuration file cann't be null");
		if (false == configurationFile.exists() || false == configurationFile.isFile()) {
			boolean b = configurationFile.createNewFile();
			if (false == b)
				throw new IOException("can't create file: " + configurationFile.getAbsolutePath());
		}
		if (false == configurationFile.canWrite())
			throw new IOException("file not writable: " + configurationFile.getAbsolutePath());
		return new FileOutputStream(configurationFile);
	}
}
